<template>
	<view class="login-container">
		<uni-forms ref="formRef" :rules="rules" :modelValue="ruleForm">
			<uni-forms-item label="手机号" required name="loginname">
				<uni-easyinput v-model="ruleForm.loginname" placeholder="请输入手机号" />
			</uni-forms-item>
			<uni-forms-item label="密码" required name="password">
				<uni-easyinput v-model="ruleForm.password" type="password" placeholder="请输入密码" />
			</uni-forms-item>
		</uni-forms>
		<button style="color:#fff;backgroundColor:#c82519;borderColor:#c82519" @click="submit">登 录</button>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app'
	import { login } from '../../api/user'
	import { ref } from 'vue'
	import { useUserStore } from '../../stores/user'

	const store = useUserStore()
	const formRef = ref(null)

	// 定义的模型
	const ruleForm = ref({
		loginname: '17704051019',
		password: '123456'
	})

	// 校验规则
	const rules = {
		loginname: {
			rules: [{
				required: true,
				errorMessage: '手机号不能为空'
			}, {
				pattern: /^1[3-9]\d{9}$/,
				errorMessage: '手机号不合法'
			}]
		},
		password: {
			rules: [{
				required: true,
				errorMessage: '密码不能为空'
			}, {
				pattern: /^\w{6,16}$/,
				errorMessage: '密码必须是6-16位'
			}]
		}
	}

	let redirect = null
	onLoad((options) => {
		redirect = options.redirect
	})

	// 提交
	const submit = async () => {
		try {
			await formRef.value.validate()

			// 就可以发请求了
			const res = await login({ loginname: ruleForm.value.loginname, password: ruleForm.value.password })
			if (res.code === 200) {
				// 存储token
				store.setToken(res.data.token)

				// 设置下tabBarItem的文字
				uni.setTabBarItem({
					index: 3,
					text: '我的'
				})

				// 提示和跳转
				uni.showToast({
					icon: 'success',
					title: res.message,
					duration: 800,
					success: () => {
						setTimeout(() => {
							if (redirect) {
								uni.reLaunch({
									url: redirect
								})
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
						}, 800)
					}
				})
			} else {
				uni.showToast({
					icon: 'error',
					duration: 800,
					title: res.message
				})
			}
		} catch (e) {
			console.log(e)
		}
	}
</script>

<style scoped lang="scss">
	.login-container {
		padding: 20rpx;
	}
</style>